//
//  TextViewController.m
//  UIKitLearn
//
//  Created by 李旭阳[产品技术中心] on 2020/5/26.
//  Copyright © 2020 李旭阳[产品技术中心]. All rights reserved.
//

#import "TextViewController.h"

//并遵循UITextViewDelegate协议，要实现func1,func2函数。
@interface TextViewController ()<UITextViewDelegate>

@property (nonatomic, weak) IBOutlet UITextView *textView;



@end

@implementation TextViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self configureTextView];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    // Listen for changes to keyboard visibility so that we can adjust the text view accordingly.
    //监听键盘可见性的变化，以便我们可以相应地调整文本视图。
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleKeyboardNotification:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleKeyboardNotification:) name:UIKeyboardWillHideNotification object:nil];
}

- (void) viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];

}
#pragma mark - Keyboard Event Notifications

- (void)handleKeyboardNotification:(NSNotification *)notification {
    NSDictionary *userInfo = notification.userInfo;
    UIViewAnimationCurve animationCurve = [userInfo[UIKeyboardAnimationCurveUserInfoKey] unsignedIntegerValue];

    // Transform the UIViewAnimationCurve to a UIViewAnimationOptions mask.
    UIViewAnimationOptions animationOptions = UIViewAnimationOptionBeginFromCurrentState;
    if (animationCurve == UIViewAnimationCurveEaseIn) {
        animationOptions |= UIViewAnimationOptionCurveEaseIn;
    }
    else if (animationCurve == UIViewAnimationCurveEaseInOut) {
        animationOptions |= UIViewAnimationOptionCurveEaseInOut;
    }
    else if (animationCurve == UIViewAnimationCurveEaseOut) {
        animationOptions |= UIViewAnimationOptionCurveEaseOut;
    }
    else if (animationCurve == UIViewAnimationCurveLinear) {
        animationOptions |= UIViewAnimationOptionCurveLinear;
    }

    NSTimeInterval animationDuration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];

    // Convert the keyboard frame from screen to view coordinates.
    CGRect keyboardScreenEndFrame = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGRect keyboardScreenBeginFrame = [[userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];

    CGRect keyboardViewEndFrame = [self.view convertRect:keyboardScreenEndFrame fromView:self.view.window];
    CGRect keyboardViewBeginFrame = [self.view convertRect:keyboardScreenBeginFrame fromView:self.view.window];
    CGFloat originDelta = keyboardViewEndFrame.origin.y - keyboardViewBeginFrame.origin.y;

    // The text view should be adjusted, update the constant for this constraint.
   // self.textViewBottomLayoutGuideConstraint.constant -= originDelta;

    [self.view setNeedsUpdateConstraints];

    [UIView animateWithDuration:animationDuration delay:0 options:animationOptions animations:^{
        [self.view layoutIfNeeded];
    } completion:nil];

    // Scroll to the selected text once the keyboard frame changes.
    NSRange selectedRange = self.textView.selectedRange;
    [self.textView scrollRangeToVisible:selectedRange];
}

#pragma mark - Configuration

- (void)configureTextView {
    
    NSString *author = @"Created by 李旭阳[产品技术中心] on 2020/5/26.";

    NSArray *args = [[NSProcessInfo processInfo] arguments];;
    NSString *argsString = [args componentsJoinedByString:@", "];

    NSDictionary *env;
    NSString *envString;
    if ([args containsObject:@"USE_NSUSERDEFAULTS"]) {
        env = [[NSUserDefaults standardUserDefaults] dictionaryRepresentation];
        envString = @"(From NSUserDefaults)";
    } else {
        env = [[NSProcessInfo processInfo] environment];
        envString = @"(From NSProcessInfo environment)";
    }

    for (NSString *key in env) {
        id value = env[key];
        NSString *line = [NSString stringWithFormat:@"%@ => %@", key, value];
        envString = [NSString stringWithFormat:@"%@\n%@", envString, line];
    }

    NSString *language = [[NSLocale preferredLanguages] firstObject];

    NSLocale *locale = [NSLocale currentLocale];
    NSString *localeId = [locale localeIdentifier];
    NSString *countryCode = [locale objectForKey: NSLocaleCountryCode];

    self.textView.text = [NSString stringWithFormat:@"%@\n\n\nPROCESS ARGUMENTS\n%@\n\n\n\nENVIRONMENT VARIABLES\n%@\n\n\n\nLANGUAGE/LOCALE\nlanguage=%@\nlocale=%@\ncountry=%@", author,argsString, envString, language, localeId, countryCode];
    //字体
    self.textView.textColor = [UIColor greenColor];
    //颜色
    self.textView.font = [UIFont systemFontOfSize:20.f];

}

#pragma mark - UITextViewDelegate

- (void)adjustTextViewSelection:(UITextView *)textView {
    // Ensure that the text view is visible by making the text view frame smaller as text can be slightly cropped at the bottom.
    // Note that this is a workwaround to a bug in iOS.
    [textView layoutIfNeeded];

    CGRect caretRect = [textView caretRectForPosition:textView.selectedTextRange.end];
    caretRect.size.height += textView.textContainerInset.bottom;
    [textView scrollRectToVisible:caretRect animated:NO];
}

//这个方法不走？
- (void)textViewDidBeginEditing:(UITextView *)textView{
    // Provide a "Done" button for the user to select to signify completion with writing text in the text view.
    UIBarButtonItem *doneBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneBarButtonItemClicked)];

    [self.navigationItem setRightBarButtonItem:doneBarButtonItem animated:YES];

    [self adjustTextViewSelection:textView];
}

- (void)textViewDidChangeSelection:(UITextView *)textView {
    [self adjustTextViewSelection:textView];
}


#pragma mark - Actions

- (void)doneBarButtonItemClicked {
    // Dismiss the keyboard by removing it as the first responder.
    [self.textView resignFirstResponder];

    [self.navigationItem setRightBarButtonItem:nil animated:YES];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
